package com.luo.bbs.ums.webapi.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.luo.bbs.ums.webapi.mapper.UserMapper;

import com.luo.pojo.ums.vo.UserLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserLoginInfoVO userLoginInfoVO = userMapper.getUserInfoByname(s);
        if (userLoginInfoVO == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        log.debug("根据用户名【{}】从数据库查询到有效的用户信息：{}", s, userLoginInfoVO);
//        UserDetails userDetails = User.builder()
//                .username(userLoginInfoVO.getUsername())
//                .password(userLoginInfoVO.getPassword())
//                .authorities("sadsadsa")
//                .credentialsExpired(false)
//                .accountLocked(false)
//                .accountExpired(false)
//                .disabled(userLoginInfoVO.getEnabled()==0)
//                .build();
        String username = userLoginInfoVO.getUsername();
        String password = userLoginInfoVO.getPassword();
        String nickname = userLoginInfoVO.getNickname();
        Integer id = userLoginInfoVO.getId();
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("/read"));
        UserUserDetails userDetails =
                new UserUserDetails(username, password, userLoginInfoVO.getEnabled() == 1, authorities);
        userDetails.setId(id);
        userDetails.setNickname(nickname);
        log.debug("即将向Spring Security返回UserDetails：{}", userDetails);
        return userDetails;
    }
}
